<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use App\WechatUser;
use Auth;
use App;
use DB;
use URL;
use Validator;
use Hash;

use HSms;

use App\Jobs\SendSms;
use App\Jobs\SendOfferSms;
use App\Jobs\SendOfferResultSms;
use App\Jobs\SendCustomSms;
use App\Services\WechatInfo;

class AuthWeChatController extends Controller
{
    /**
     * 显示登录页面
     *
     * @return \Illuminate\View\View
     */
    public function login(Request $request)
    {
        session()->forget('forget_user');
        session()->forget('forget_vcode');
        session()->forget('forget_auth');
        return view('auth.wechat_login');
    }

    public function auth(Request $request)
    {
        $credentials = $request->only(['username', 'password']);
        $credentials = array_map('trim', $credentials);
        if (Auth::attempt($credentials)) {
            $auth_user = auth()->user();
            if ( ! $auth_user->allow_login) {
                auth()->logout();
                return redirect()->route('auth.wechat.login')->withInput()->withErrors(['message' => ['您输入的帐号已经被管理员锁定，目前无法登录']]);
            }
            switch ($auth_user->type) {
                case 'supplier':
                    $user_profile = $auth_user->supplier;
                    break;
                case 'staff':
                    $user_profile = $auth_user->staff;
                    auth()->logout();
                    return redirect()->route('auth.wechat.login')->withInput()->withErrors(['message' => ['您输入的用户名不是供应商，请核对后重新登录']]);
                    break;
                default:
                    auth()->logout();
                    App::abort(403, 'User Type is unkown!');
                    break;
            }
            $addition = $user_profile->addition;
            if ( ! empty($addition)) {
                $addition = json_decode($addition);
            } else {
                $addition = [];
            }
            $user_profile->addition = $addition;
            session(['user_profile' => $user_profile]);
            if ($auth_user->type == 'supplier' and !$auth_user->accept_agreement) {
                // 返回信息
               //  return redirect()->route('dashboard.agreement');
                return redirect()->route('auth.wechat.login')->withInput()->withErrors(['message' => ['您还没有同意使用易诚荟交易平台，请在PC端同意后再登录']]);
            }

            // 登录后 写入 微信绑定信息。
            $wechat_info = $request->only(['access_token','openid']);
            $openid = $wechat_info['openid'];
            $access_token = $wechat_info['access_token'];
            
            $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $res= file_get_contents($get_user_info_url );
            $user_obj = json_decode($res,true);

            // 加密后存储。
            $user_obj['user_id'] = $auth_user->id;
            $user_obj['user_password'] = urlencode($credentials['password']);
            $user_obj['openid'] = $openid;

            // 删除元素
            unset($user_obj['privilege']);
            unset($user_obj['language']);
            
            // 新建绑定关系
            $WechatUser = WechatUser::updateOrCreate($user_obj);

            // 发送微信模板消
            //$wechat_info = new WechatInfo();
            //$result = $wechat_info->send_template_message($openid, $auth_user->username);

            if ($WechatUser) {
                return redirect()->route('todolist.welcome');
            }
        }
        return redirect()->route('auth.wechat.login')->withInput()->withErrors(['message' => ['您输入的用户名与密码不匹配，请核对后重新登录']]);
    }

    // 微信回调页面
    public function loginCheck()
    {
        // TODO 取得微信信息
        $appid = 'wx0f8d99209d7c5573';
        $secret = 'c317d16ccf6a335e0a67e12128d6be68';
        if (empty( $_GET['code'])) {
            // TODO 转移到错误页面
            return view('errors.wechat_error')
                ->with('error_message_info','没有接收到微信用户code');
        }

        $code = $_GET['code'];

        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $html = file_get_contents($get_token_url);
        $json_obj = json_decode($html,true);
        $access_token = $json_obj['access_token'];
        $openid = $json_obj['openid'];

        if (empty($access_token) or empty($openid)) {
            // TODO 转移到错误页面
            return view('errors.wechat_error')
                ->with('error_message_info','没有接收到微信用户openid或access_token');
        }

        // 根据openid 去 WechatUser表中检索是否有该用户信息
        $wechat_user = WechatUser::where('openid','=',$openid)->first();

        if (!empty($wechat_user->user_id)) {

            // 取得微信关联用户信息
            $user = User::whereId($wechat_user->user_id)->first();
            
            // 解密 取得密码
            $user_name = $user->username;
            $password = urldecode($wechat_user->user_password);

            $credentials['username'] = $user_name;
            $credentials['password'] = $password;

            if (Auth::attempt($credentials)) {

                // 登录
                // 是否需要其它数据处理？？
                // 保存
                // 发送微信模板消
                $wechat_info = new WechatInfo();

                //
                //$wechat_info->set_menu();

                $result = $wechat_info->send_template_message($openid, $user_name);
                
                return redirect()->route('todolist.welcome');
            }else {
                //  登录不成功，进入登录页面。
                return view('auth.wechat_login')
                    ->with('access_token',$access_token)
                    ->with('openid',$openid);
            }

        } else {

            //  没有绑定信息，进入登录页面。
            return view('auth.wechat_login')
                ->with('access_token',$access_token)
                ->with('openid',$openid);
        }

//        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
//        $res= file_get_contents($get_user_info_url );
//        $user_obj = json_decode($res,true);
//
//        $openid = $user_obj['openid'];
//        $nickname = $user_obj['nickname'];
//        $sex = $user_obj['sex'];
//        $city = $user_obj['city'];
//        $province = $user_obj['province'];
//        $country = $user_obj['country'];
//        $headimgurl = $user_obj['headimgurl'];

        // 利用微信openid 去数据库查找匹配信息
        // 有的 时候 写入session直接登录
        // 没有的时候 进行数据写入并绑定。
        // 解除绑定 删除微信信息。
    }

    public function logout()
    {
        session()->forget('user_type');
        auth()->logout();
        return redirect()->route('auth.wechat.login');
    }

    // 微信解除绑定
    public function unbindWechat()
    {
        // 删除绑定信息
        // 根据openid 去 WechatUser表中检索是否有该用户信息
        $auth_user = auth()->user();
        $wechat_user = WechatUser::where('user_id','=',$auth_user->id)->first();

        if (!empty($wechat_user) and !is_null($wechat_user->openid)) {

            //WechatUser::whereDeletedAt('openid','=',$wechat_user->openid);
            DB::table('wechat_users')->where('openid', '=', $wechat_user->openid)->delete();

        }
        session()->forget('user_type');
        auth()->logout();

        return view('setting.wechat_logout');
    }
}
